<template>
  <div class="table-page">
    <vxe-grid
      ref="gridTable"
      round
      show-header-overflow
      show-overflow
      :data="displayedData"
      :row-style="tableRowStyle"
      :border="border"
      :auto-resize="true"
      :loading="tableLoading"
      :size="size === 'default' ? 'small' : size === 'small' ? 'mini' : size === 'large' ? 'medium' : ''"
      :height="height"
      :columns="tableColumns"
      :scroll-y="{ enabled: true, gt: 0 }"
      :checkbox-config="{ checkField: 'checkbox', highlight: true, range: true, trigger: 'default' }"
      :column-config="{ resizable: true, useKey: true }"
      :row-config="{ isCurrent: true, keyField: 'Record_ID', useKey: true, isHover: true }"
      :menu-config="tableMenu"
      :toolbar-config="toolbarConfig"
      :print-config="{}"
      :import-config="{}"
      :export-config="{}"
      @menu-click="rightMenuClick"
      @cell-click="cellClick"
      @cell-dblclick="cellDblclick"
      @checkbox-change="checkboxChange"
      @checkbox-all="checkboxAll"
      @checkbox-range-end="checkboxRangeEnd"
      @keydown="handleKeydown"
    >
      <template #toolbarButtons>
        <slot name="toolbarButtons"></slot>
      </template>
      <!-- 自定义操作列标题模板 -->
      <template #FourAspect_Pass_default="{ row }">
        <div>
          {{ !row.FourAspect_Pass ? "未检测" : row.FourAspect_Pass == 2 ? "通过" : "未通过" }}
        </div>
      </template>
      <template #operation_title="{ column }">
        <div class="optionsColumn">
          <span>{{ column.title.text }}</span>
          <span v-if="column.title.count !== undefined">({{ column.title.count }})</span>
          <!-- <el-button :icon="tableSearch ? 'View' : 'Hide'" circle @click="emit('trigger')" /> -->
        </div>
      </template>
      <!-- Status字段 -->
      <template #Status_default="{ row }">
        <el-tooltip effect="dark" :content="row.MarkContent" placement="top" v-if="row.MarkContent">
          <span :class="['circle', dynamicClass[row.Status]['class']]">{{ dynamicClass[row.Status]["name"] }}</span>
        </el-tooltip>
        <span v-else :class="['circle', dynamicClass[row.Status]['class']]">{{ dynamicClass[row.Status]["name"] }}</span>
      </template>
      <!-- IsLock字段 -->
      <template #IsLock_default="{ row }">
        <el-icon v-if="Number(row.IsLock)"><Lock /></el-icon>
        <el-icon v-else><Unlock /></el-icon>
      </template>
      <template #operation="{ row }">
        <div class="columOptions">
          <a-dropdown v-if="props.childData.length > 0">
            <el-button icon="FolderOpened" link type="primary"> 卷内 </el-button>
            <template #overlay>
              <a-menu>
                <a-menu-item v-for="(item, index) in childData" :key="index">
                  <el-button link type="primary" @click="toSublevel(row, item)">
                    {{ item.FMT_Name }}
                  </el-button>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <el-button icon="View" link type="primary" @click="viewFullText(row)"> 全文 </el-button>
          <el-button
            icon="Coin"
            v-if="fmtData.filter((v:any)=>v.FMT_ID === row.FMT_ID )[0]?.FMT_ShowMetaData"
            link
            type="primary"
            @click="showMetaData(row)"
          >
            元数据
          </el-button>
          <el-button icon="Document" link type="primary" @click="viewFourAspect(row)"> 四性 </el-button>
        </div>
      </template>
    </vxe-grid>
    <div class="loadImg" v-if="paginationShow && hasTableData">
      <el-tooltip class="item" effect="dark" content="下一页" placement="left">
        <img @click="pageNext" style="width: 30px; height: 30px; margin-bottom: 5px; margin-left: 2px" :src="nextImgUrl" alt="" />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="全部数据" placement="left">
        <img @click="pageAll" style="width: 35px" :src="allImgUrl" alt="" />
      </el-tooltip>
    </div>
    <!-- 弹窗组件 -->
    <el-dialog width="300" v-model="dialogVisible" title="模糊查找" @close="closeSearchDialog" :modal="false" :draggable="true">
      <el-input v-model="searchContent" placeholder="输入关键词进行查找"></el-input>
      <template #footer>
        <el-button type="primary" @click="searchTable">查找</el-button>
        <el-button @click="searchNext">查找下一个</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref, watch, computed, onUnmounted, nextTick, PropType, onMounted } from "vue";
import { VxeGridInstance, VxeUI } from "vxe-table";
import { useGlobalStore } from "@/stores/modules/global";
import { customFields } from "../dataType";
import { useDynamicStore } from "@/stores/modules/dynamic";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useCatalogStore } from "@/stores/modules/catalog";
import { useUserStore } from "@/stores/modules/user";
import { columnCoverter } from "@/views/system/dynamicMain/ts/until";
import { useRoute } from "vue-router";
import dtime from "moment";
import ACrypto from "@/utils/crypto";
import { cloneDeep } from "lodash-es";
import Sortable from "sortablejs";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useFind } from "./useFind";

// import myVM from "./vm";

const { proxy } = useCurrentInstance();
const props = defineProps({
  name: {
    type: String,
    default: () => ""
  },
  father: {
    type: Object as PropType<object>,
    default: () => ({})
  },
  childs: {
    type: Object as PropType<object>,
    default: () => ({})
  },
  height: {
    type: String || Number,
    default: () => {
      return "auto";
    }
  },
  border: {
    type: Boolean,
    default: () => {
      return true;
    }
  },
  columns: {
    type: Array,
    default: () => {
      return [];
    }
  },
  childData: {
    type: Array as any,
    default: () => {
      return [];
    }
  },
  hasTableData: {
    // 只做判断使用
    type: Boolean,
    default: () => {
      return false;
    }
  },
  loading: {
    type: Boolean,
    default: () => {
      return false;
    }
  },
  paginationShow: {
    // 是否显示分页
    type: Boolean,
    default: () => {
      return false;
    }
  },
  tableMenu: {
    type: Object,
    default: () => {
      return {
        // enabled: true,
        // className: 'my-menus',
        // body: {
        //   options: [
        //     [
        //       { code: 'copy', name: '测试按钮', prefixIcon: 'fa fa-copy', className: 'my-copy-item' }
        //     ]
        //   ]
        // }
      };
    }
  },
  columnType: {
    type: String,
    default: () => {
      return "folder";
    }
  },
  fmtData: {
    type: Array,
    default: () => {
      return [];
    }
  },
  toolbarConfigVisible: {
    type: Boolean,
    default: false
  },
  tableSearch: {
    type: Boolean,
    default: false
  }
});

// const MyVM = new myVM(props.name, props.father, props.childs);

const emit = defineEmits([
  "refresh",
  "trigger",
  "rowClick",
  "rowdblClick",
  "selectChange",
  "pageChange",
  "viewFullText",
  "toSublevel",
  "pageNext",
  "pageAll",
  "menuClick",
  "showMetaData",
  "showFourAspectRecords"
]);
const dynamicClass = reactive<any>({
  0: { class: "circle-bg0", name: "删除" },
  1: { class: "circle-bg1", name: "预归" },
  11: { class: "circle-bg11", name: "待审" },
  12: { class: "circle-bg12", name: "退回" },
  2: { class: "circle-bg2", name: "整理" },
  21: { class: "circle-bg21", name: "待存" },
  22: { class: "circle-bg22", name: "退整" },
  3: { class: "circle-bg3", name: "保存" }
});
const nextImgUrl = new URL("@/assets/images/next.png", import.meta.url).href;
const allImgUrl = new URL("@/assets/images/all.png", import.meta.url).href;
const globalStore = useGlobalStore();
const dynamicStore = useDynamicStore();
const dictionryStore = useDictionryStore();
const catalogStore = useCatalogStore();
const userStore = useUserStore();
// 系统色
const isDark = computed(() => (globalStore.isDark ? true : false));
if (isDark.value) {
  VxeUI.setTheme("dark");
} else {
  VxeUI.setTheme("light");
}
const size = computed<any>(() => globalStore.assemblySize); //尺寸
const gridTable = ref({} as VxeGridInstance); //表格实例
//vxt-table配置
// const tableColumns: any = ref([]); //表头
const tableLoading = ref(false);
// 点击时间间隔
const timer = ref();
// 操作列渲染防抖器
const columnTimer = ref<any>(null);

let sortable2: any;

const handleRefresh = () => {
  if (props.name === "tabbarRef") {
    emit("refresh");
  }
};
// 工具栏配置
const toolbarConfig = reactive({
  refresh: {
    icon: "vxe-icon-refresh",
    iconLoading: "vxe-icon-refresh roll",
    // queryMethod: handleRefresh
    queryMethod: () => emit("refresh")
  },
  import: {
    icon: "vxe-icon-cloud-upload"
  },
  export: {
    icon: "vxe-icon-cloud-download"
  },
  print: {
    icon: "vxe-icon-print"
  },
  zoom: {
    iconIn: "vxe-icon-fullscreen",
    iconOut: "vxe-icon-minimize"
  },
  custom: {
    icon: "vxe-icon-menu"
  },
  slots: {
    buttons: "toolbarButtons"
  }
});

// ****************** 搜索功能 ******************
// 弹框是否显示
const dialogVisible = ref(false);
const displayedData = ref<any>(); // 查找功能
const { searchContent, searchTable, searchNext, foundRows, currentIndex, highlightAndScrollToRow } = useFind(
  displayedData,
  gridTable
);
// ****************** 搜索功能 ******************

// 四性检测记录展示/抛出传递给父组件
const viewFourAspect = (row: any) => {
  console.log(row);
  emit("showFourAspectRecords", row);
};

// 表格事件
// 单击事件
const cellClick = ({ row, rowIndex, column }: { row: any; rowIndex: number; column: any }) => {
  //setTimeout 计时器(延时器)
  clearTimeout(timer.value); //清除第一次的单击事件
  //500毫秒之后运行点击事件
  timer.value = setTimeout(() => {
    // 筛除多选时单击触发操作
    if (!column.property) {
      return;
    }
    emit("rowClick", { row, rowIndex });
  }, 30);
};
// 双击事件
const cellDblclick = ({ row, rowIndex, column }: { row: any; rowIndex: number; column: any }) => {
  clearTimeout(timer.value); //清除第二次的单击事件
  // 筛除多选时单击触发操作
  if (!column.property) {
    return;
  }
  emit("rowdblClick", { row, rowIndex });
};
// 勾选
const checkboxChange = (params: { records: any }) => {
  emit("selectChange", params.records);
};
// 全部勾选
const checkboxAll = (params: { records: any }) => {
  emit("selectChange", params.records);
};
// 快捷勾选
const checkboxRangeEnd = (params: { records: any }) => {
  emit("selectChange", params.records);
};
// 清除全部全选操作
const clearCheckboxRow = () => {
  gridTable.value.clearCurrentRow();
  gridTable.value.clearCheckboxRow();
};
// 多选操作勾选某行
const setCheckboxRow = (rows: any, checked: boolean) => {
  if (rows.length === 0) {
    // 清除全部多选选择
    clearCheckboxRow();
  } else {
    clearCheckboxRow();
    gridTable.value.setCheckboxRow(rows, checked);
  }
};
// 查看全文页面
const viewFullText = (row: any) => {
  emit("viewFullText", row);
};
// 跳转子页面
const toSublevel = (row: any, item?: any) => {
  emit("toSublevel", row, item);
};
// 右键事件
const rightMenuClick = ({ menu, row, column }: any) => {
  emit("menuClick", { menu, row, column });
};

// 局部加载页面数据
const reloadData = (data: any) => {
  displayedData.value = data;
};
// 表格字段转换
// const formatter = ({ row, column, cellValue }: any): any => {
//   const catalogList = catalogStore.catalogList;
//   let ruleList = [];
//   if (props.columnType === "folder") {
//     ruleList = dynamicStore.visibleConfig.FieldRule.filter((v: any) => v.FR_RuleType === "display");
//   } else {
//     ruleList = dynamicStore.childVisibleConfig.FieldRule.filter((v: any) => v.FR_RuleType === "display");
//   }
//   const tempObj = ruleList.find((v: any) => v.FR_TableField === column.field);
//   let result = null;
//   let param = null;

//   if (tempObj) {
//     // 字典转换
//     param = tempObj.FR_Rule.split(":")[1];
//     if (tempObj.FR_Rule.includes("dictionary:")) {
//       result = columnCoverter(tempObj.FR_Rule, cellValue);
//     } else if (tempObj.FR_Rule.toLowerCase().includes("datetime:")) {
//       // 时间转换
//       result = dtime(row[tempObj.FR_TableField]).format(param);
//     } else if (tempObj.FR_Rule.toLowerCase().includes("userinfo:")) {
//       // 人员的id转换
//       const temp = userStore.getUserList.find((v: any) => v.U_ID === cellValue);
//       result = temp ? temp[param] : "";
//     } else if (tempObj.FR_Rule.toLowerCase().includes("catalogconvert:")) {
//       // 分类id转换
//       const temp = catalogList.find((v: any) => v.Catalog_ID && v.Catalog_ID === cellValue);
//       result = temp ? temp[param] : "";
//     } else if (tempObj.FR_Rule.toLowerCase().includes("orgconvert:")) {
//       const temp = catalogList.find((v: any) => v[tempObj.Field_Name] === cellValue);
//       result = temp ? temp[param] : "";
//     } else if (tempObj.FR_Rule.toLowerCase().includes("jm")) {
//       // 对加密字段转换
//       result = ACrypto.getSS(row[tempObj.FR_TableField]);
//     } else if (tempObj.FR_Rule.toLowerCase().includes("tozh")) {
//       if (row[tempObj.FR_TableField]) {
//         result = "是";
//       } else {
//         result = "否";
//       }
//     }
//   }
//   row[column.field] = result ? result : cellValue;
// };
// 表格字段转换
const formatter = ({ row, column, cellValue }: any): any => {
  const catalogList = catalogStore.catalogList;
  let ruleList = [];
  if (props.columnType === "folder") {
    ruleList = dynamicStore.visibleConfig.FieldRule.filter((v: any) => v.FR_RuleType === "display");
  } else {
    ruleList = dynamicStore.childVisibleConfig.FieldRule.filter((v: any) => v.FR_RuleType === "display");
  }
  const tempObj = ruleList.find((v: any) => v.FR_TableField === column.property);
  let result = null;
  let param = null;

  if (tempObj) {
    // 字典转换
    param = tempObj.FR_Rule.split(":")[1];
    if (tempObj.FR_Rule.includes("dictionary:")) {
      result = columnCoverter(tempObj.FR_Rule, cellValue);
    } else if (tempObj.FR_Rule.toLowerCase().includes("datetime:")) {
      // 时间转换
      result = dtime(row[tempObj.FR_TableField]).format(param);
    } else if (tempObj.FR_Rule.toLowerCase().includes("userinfo:")) {
      // 人员的id转换
      const temp = userStore.getUserList.find((v: any) => v.U_ID === cellValue);
      result = temp ? temp[param] : "";
    } else if (tempObj.FR_Rule.toLowerCase().includes("catalogconvert:")) {
      // 分类id转换
      const temp = catalogList.find((v: any) => v.Catalog_ID && v.Catalog_ID === cellValue);
      console.log(temp, param);
      result = temp ? temp[param] : "";
    } else if (tempObj.FR_Rule.toLowerCase().includes("orgconvert:")) {
      const temp = catalogList.find(v => v[tempObj.Field_Name] === cellValue);
      result = temp ? temp[param] : "";
    } else if (tempObj.FR_Rule.toLowerCase().includes("jm")) {
      // 对加密字段转换
      result = ACrypto.getSS(row[tempObj.FR_TableField]);
    } else if (tempObj.FR_Rule.toLowerCase().includes("tozh")) {
      if (row[tempObj.FR_TableField]) {
        result = "是";
      } else {
        result = "否";
      }
    }
  }
  if (result) {
    return result;
  }
  return cellValue;
};
// 下一页
const pageNext = () => {
  emit("pageNext");
};
// 全部
const pageAll = () => {
  emit("pageAll");
};
// 给表格加上自定义样式
const tableRowStyle = ({ row, rowIndex }: any) => {
  Object.defineProperty(row, "rowIndex", {
    // 给每一行添加不可枚举属性rowIndex来标识当前行
    value: rowIndex,
    writable: true,
    enumerable: false
  });
  if (row.MarkColor) {
    return { background: row.MarkColor };
  } else {
    return {};
  }
};
let sortable1: any;

const rowDrop = (data: any[] = []) => {
  const $table = gridTable.value;
  sortable1 = Sortable.create($table.$el.querySelector(".body--wrapper>.vxe-table--body tbody"), {
    handle: ".vxe-body--column",
    onEnd: sortableEvent => {
      const newIndex = sortableEvent.newIndex as number;
      const oldIndex = sortableEvent.oldIndex as number;
      const currRow = dynamicStore.tableData.splice(oldIndex, 1)[0];
      dynamicStore.tableData.splice(newIndex, 0, currRow);
    }
  });
};
// 显示元数据弹框
const showMetaData = (row: any) => {
  emit("showMetaData", row);
};
// 列拖动
const columnDrop2 = () => {
  const $grid = gridTable.value;
  sortable2 = Sortable.create($grid.$el.querySelector(".body--wrapper>.vxe-table--header .vxe-header--row"), {
    handle: ".vxe-header--column",
    onEnd: sortableEvent => {
      const targetThElem = sortableEvent.item;
      const newIndex = sortableEvent.newIndex as number;
      const oldIndex = sortableEvent.oldIndex as number;
      const { fullColumn, tableColumn } = $grid.getTableColumn();
      const wrapperElem = targetThElem.parentNode as HTMLElement;
      const newColumn = fullColumn[newIndex];
      const oldColumn = fullColumn[oldIndex];

      if (newColumn.fixed || oldColumn.fixed) {
        // 错误的移动
        const oldThElem = wrapperElem.children[oldIndex] as HTMLElement;
        if (newIndex > oldIndex) {
          wrapperElem.insertBefore(targetThElem, oldThElem);
        } else {
          wrapperElem.insertBefore(targetThElem, oldThElem ? oldThElem.nextElementSibling : oldThElem);
        }
        proxy.$message.warning("固定列不允许拖动!");
        return;
      } else if (newColumn.type === "checkbox" || oldColumn.type === "checkbox") {
        // 错误的移动
        const oldThElem = wrapperElem.children[oldIndex] as HTMLElement;
        if (newIndex > oldIndex) {
          wrapperElem.insertBefore(targetThElem, oldThElem);
        } else {
          wrapperElem.insertBefore(targetThElem, oldThElem ? oldThElem.nextElementSibling : oldThElem);
        }
        proxy.$message.warning("选择框不允许拖动!");
        return;
      }
      // 获取列索引 columnIndex > fullColumn
      const oldColumnIndex = $grid.getColumnIndex(tableColumn[oldIndex]);
      const newColumnIndex = $grid.getColumnIndex(tableColumn[newIndex]);
      // 移动到目标列
      const currRow = fullColumn.splice(oldColumnIndex, 1)[0];
      fullColumn.splice(newColumnIndex, 0, currRow);
      $grid.loadColumn(fullColumn);
    }
  });
};

// 检测数据中是否含有符合项
const checkFmtData = (arr: any[], fmtData: any[]): boolean => {
  return arr.some(row => {
    const match = fmtData.find((v: any) => v.FMT_ID === row.FMT_ID);
    return match?.FMT_ShowMetaData || false;
  });
};

// 计算操作列宽度（依赖所有相关 props）
const operationColumnWidth = computed(() => {
  const { childData, fmtData, columns } = props;
  const hasChildData = childData.length > 0;
  const hasValidFmtData = checkFmtData(columns, fmtData);
  if (hasChildData && hasValidFmtData) {
    return "290px";
  } else if (hasChildData || hasValidFmtData) {
    return "222px";
  } else {
    return "155px";
  }
});
// 动态生成完整的列配置（计算属性）
const tableColumns = computed(() => {
  const cols = props.columns.map((item: any) => {
    if (customFields.includes(item.Field_Name)) {
      return {
        type: "html",
        field: item.Field_Name,
        title: item.DDM_CNName,
        width: item.DDM_DisplayWidth,
        align: "center",
        sortable: true,
        slots: { default: `${item.Field_Name}_default` }
      };
    } else {
      return {
        type: "html",
        field: item.Field_Name,
        title: item.DDM_CNName,
        width: item.DDM_DisplayWidth,
        sortable: true,
        formatter: formatter
      };
    }
  });

  // 添加复选框列和操作列
  return [
    { type: "checkbox", width: 55 },
    ...cols,
    {
      title: { text: "操作", count: undefined },
      width: operationColumnWidth.value,
      fixed: "right",
      slots: {
        default: "operation",
        header: "operation_title"
      }
    }
  ];
});
// 简化后的 watch（仅用于调试或必要操作）
watch(
  () => props.columns,
  newValue => {
    console.log("Columns updated:", newValue);
  },
  { deep: true, immediate: true }
);
watch(
  () => props.loading,
  (newVal, oldVal) => {
    tableLoading.value = newVal;
  },
  {
    immediate: true // 立即执行
  }
);
// 检测主表格数据变化
watch(
  () => [...dynamicStore.tableData],
  (newValue, oldValue) => {
    tableColumns.value = tableColumns.value.map((v: any) => {
      if (v.title && v.title.text === "操作" && props.columnType === "folder") {
        v.title.count = newValue.length;
      }
      return v;
    });
  }
);
let initTime: any;
nextTick(() => {
  // 加载完成之后在绑定拖动事件
  initTime = setTimeout(() => {
    columnDrop2();
    // rowDrop();
  }, 500);
});

onUnmounted(() => {
  clearTimeout(initTime);
  if (sortable2) {
    sortable2.destroy();
    // sortable1.destroy();
  }
});

// 打开查找弹窗
const openSearchDialog = () => {
  dialogVisible.value = true;
};

// 打开查找弹窗
const closeSearchDialog = () => {
  highlightAndScrollToRow(foundRows.value[currentIndex.value], false);
  searchContent.value = "";
  dialogVisible.value = true;
};
// 监听键盘事件
const handleKeydown = (event: { ctrlKey: any; key: string; preventDefault: () => void }) => {
  // 检查是否按下了 Enter 键
  if (event.key === "Enter") {
    openSearchDialog(); // 打开查找弹窗
  }
};
const name = ref(props.Name);
defineExpose({ setCheckboxRow, reloadData, cellClick, name });
</script>

<style lang="scss">
@import "@/styles/vxe-table.scss";
.highlight {
  background-color: yellow;
}
.circle {
  display: inline-block;
  width: 28px;
  height: 18px;
  font-size: 12px;
  line-height: 18px;
  text-align: center;
  border-radius: 2px;
}
.circle-bg1,
.circle-bg11,
.circle-bg2,
.circle-bg21,
.circle-bg3 {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-6);
  box-shadow: 0 0 3px var(--el-color-primary);
}
.circle-bg12,
.circle-bg22 {
  color: #ffffff;
  background: red;
  box-shadow: 0 0 3px var(--el-color-primary);
}
.table-page {
  position: relative;
  height: 100%;
  .loadImg {
    position: absolute;
    top: 36px;
    right: 15px;
    bottom: 0;
    z-index: 999;
    display: flex;
    flex-direction: column;
    height: 50%;
    margin: auto;
  }
  .ant-spin-nested-loading {
    margin: 0;
  }
  .vxe-grid--table-container {
    position: relative;
    .optionsColumn {
      .el-button {
        position: absolute;
        top: 4px;
        right: -2px;
      }
    }
  }
}
// .columOptions {
//   width: 270px;
// }
</style>
